package com.wing.util;

import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.tdmq.v20200217.TdmqClient;
import com.tencentcloudapi.tdmq.v20200217.models.CreateSubscriptionRequest;
import com.tencentcloudapi.tdmq.v20200217.models.CreateSubscriptionResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.pulsar.client.api.PulsarClientException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class TencentCloudApiUtil {

    @Value("${com.tencentcloudapi.secretId}")
    private String secretId;

    @Value("${com.tencentcloudapi.secretKey}")
    private String secretKey;

    @Value("${com.tencentcloudapi.endpoint}")
    private String endpoint;

    @Value("${com.tencentcloudapi.region}")
    private String region;

    /**
     * 初始化云TDMP队列API
     * @throws PulsarClientException
     */
    public TdmqClient init() {
        try{
            // 实例化一个认证对象，入参需要传入腾讯云账户secretId，secretKey,此处还需注意密钥对的保密
            // 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取
            Credential cred = new Credential(secretId, secretKey);
            // 实例化一个http选项，可选的，没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint(endpoint);
            // 实例化一个client选项，可选的，没有特殊需求可以跳过
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            // 实例化要请求产品的client对象,clientProfile是可选的
            return new TdmqClient(cred, region, clientProfile);
        } catch (Exception e) {
            log.error("初始化HTTPTDMP失败:" ,e);
        }
        return null;
    }

    /**
     * 创建订阅关系
     * @param req
     * @return
     */
    public CreateSubscriptionResponse createSubscription(CreateSubscriptionRequest req){
        try{
            TdmqClient client = init();
            //// 实例化一个请求对象,每个接口都会对应一个request对象
            //CreateSubscriptionRequest req = new CreateSubscriptionRequest();
            //req.setEnvironmentId("test");
            //req.setTopicName("test");
            //req.setSubscriptionName("sub2");
            //req.setIsIdempotent(true);
            //req.setClusterId("pulsar-a8ea4brdvkd2");
            //req.setAutoCreatePolicyTopic(true);
            // 返回的resp是一个CreateSubscriptionResponse的实例，与请求对象对应
            CreateSubscriptionResponse resp = client.CreateSubscription(req);
            //if(null != resp && !resp.getResult()){
            //
            //}
            // 输出json格式的字符串回包
            log.info("创建订阅关系响应:" + CreateSubscriptionResponse.toJsonString(resp));
            return resp;
        } catch (TencentCloudSDKException e) {
            log.error("创建订阅关系异常:", e);
        }
        return null;
    }

}
